package com.pxx.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxx.common.utils.PageResult;
import com.pxx.item.mapper.BrandMapper;
import com.pxx.item.mapper.CategoryMapper;
import com.pxx.item.pojo.Brand;
import com.pxx.item.pojo.Category;
import com.pxx.item.service.BrandService;
import com.pxx.item.service.CategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Override
    public PageResult queryBrandByPage(Integer page, Integer rows, String sortBy, Boolean desc, String key) {
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isBlank(key)){
            queryWrapper.like("name",key);
        }
        Page<Brand> pageInfo = new Page<>(page,rows);
        if(!StringUtils.isBlank(sortBy)){
            pageInfo.addOrder(desc? OrderItem.desc(sortBy):OrderItem.asc(sortBy));
        }
        Page<Brand> pageInfoData = brandMapper.selectPage(pageInfo, queryWrapper);
        if(pageInfoData.getTotal()==0){
            return new PageResult<Brand>();
        }
        PageResult<Brand> brandPageResult = new PageResult<>(pageInfoData.getTotal(),pageInfoData.getPages(),pageInfoData.getRecords());
        return brandPageResult;
    }

    @Transactional
    @Override
    public void saveBrand(Brand brand, List<Long> cids) {
        int inserted = brandMapper.insert(brand);
        if(inserted>0){
            cids.forEach(cid->{
                brandMapper.saveCategoryAndBrand(cid,brand.getId());
            });
        }
    }
}
